<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">
      <el-form-item label="创建日期" prop="createdAt">
      <template #label>
        <span>
          创建日期
          <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </span>
      </template>
      <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始日期" :disabled-date="time=> searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"></el-date-picker>
       —
      <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束日期" :disabled-date="time=> searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"></el-date-picker>
      </el-form-item>


 <!-- 计算付费卡点弹框 -->
 <el-dialog v-model="calculateCheckpointDialog" style="width: 900px" lock-scroll :before-close="closecalculateCheckpointDialog" title="付费卡点" destroy-on-close>
     <div class="gva-search-box">
      <el-form-item>
         <p>未充值付费卡点</p>
      </el-form-item>
        <el-table
          ref="form"
          :data="unpaidCardPointsList"
          v-loading="listLoading"
          style="width: 100%"
          @selection-change="setSelectRows"
        >
          <el-table-column
            label="充值模板商品"
            width="260"
          >
          <template #default="scope">
            {{ scope.row.name }} - 商品{{ scope.row.shopNum }} - {{scope.row.cost}}元
          </template>
        </el-table-column>
          <el-table-column
            label="商品信息"
            width="260"
          >
          <template #default="scope">
            <div v-if="scope.row.type == 1">
              金额: {{ scope.row.cost }}元  看点:{{ scope.row.amount + scope.row.give }} 
          </div>
           <div v-else-if="scope.row.type == 2">
              金额: {{ scope.row.cost }}元  VIP天数: {{ scope.row.vpDay }} 天
           </div>
          </template>
          </el-table-column>
          <el-table-column
            label="预计可播放付费集数"
            width="270"
          >
          <template #default="scope">
              <div v-if="scope.row.type == 1">
                {{ scope.row.episodes }}集 【剩余看点: {{scope.row.remainingHighlights}}】
              </div>
              <div v-else-if="scope.row.type == 2">
                 全集:({{ scope.row.totalCnt }}集)
              </div>
            </template>
          </el-table-column>
        </el-table>
      <br>
      <el-form-item>
         <p>已充值付费卡点</p>
      </el-form-item>
       <el-table
          ref="form"
          :data="unpaidCardPointsListV2"
          v-loading="listLoading"
          style="width: 100%"
          @selection-change="setSelectRows"
        >
          <el-table-column
            label="充值模板商品"
            width="260"
            >
            <template #default="scope">
               {{ scope.row.name }} - 商品 {{ scope.row.shopNum }} - {{scope.row.cost}}元
          </template>
       </el-table-column>  
          <el-table-column
            label="商品信息"
            width="260"
            >
            <template #default="scope">
              <div v-if="scope.row.type == 1">
                 金额: {{ scope.row.cost }}元  看点:{{ scope.row.amount + scope.row.give }} 
              </div>
              <div v-else-if="scope.row.type == 2">
                 金额: {{ scope.row.cost }}元  VIP天数: {{  scope.row.vpDay }} 天
              </div>
          </template>
            </el-table-column>
          <el-table-column
            label="预计可播放付费集数"
            width="270"
          >
          <template #default="scope">
            <div v-if="scope.row.type == 1">
                {{ scope.row.episodes }}集 【剩余看点: {{scope.row.remainingHighlights}}】
              </div>
              <div v-else-if="scope.row.type == 2">
                 全集:({{ scope.row.totalCnt }}集)
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
      
      <el-form-item label="配置名称" prop="name">
         <el-input v-model="searchInfo.name" placeholder="搜索条件" />

        </el-form-item>
           <!-- <el-form-item label="短剧" prop="movieId">
            <el-select v-model="searchInfo.movieId" clearable placeholder="请选择" @clear="()=>{searchInfo.movieId=undefined}">
              <el-option v-for="(item,key) in switchOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
            </el-form-item> -->
            <el-form-item
          label="短剧"
          prop="movieId"
        >
          <el-select
            v-model="searchInfo.movieId"
            style="width:194px" placeholder="请选择"
          >
            <el-option
              v-for="item in movielist"
              :key="item.ID"
              :value="item.ID"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="回传配置"
          prop="callbackConfigId"
        >
          <el-select
            v-model="searchInfo.callbackConfigId"
            style="width:194px" placeholder="请选择"
          >
            <el-option
              v-for="item in convruleslist"
              :key="item.ID"
              :value="item.ID"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="平台类型：" prop="platId">
            <el-select v-model="searchInfo.platId" clearable placeholder="请选择" @clear="()=>{searchInfo.platId=0}">
              <el-option v-for="(item,key) in platOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
            </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
        <div class="gva-btn-list">
            <!-- <el-button type="primary" icon="plus" @click="openDialog">新增</el-button> -->
            <el-button type="primary" icon="Histogram" @click="getStatistics()">数据汇总统计</el-button>

            <!-- <el-popover v-model:visible="deleteVisible" :disabled="!multipleSelection.length" placement="top" width="160">
            <p>确定要删除吗？</p>
            <div style="text-align: right; margin-top: 8px;">
                <el-button type="primary" link @click="deleteVisible = false">取消</el-button>
                <el-button type="primary" @click="onDelete">确定</el-button>
            </div>
            <template #reference>
                <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="deleteVisible = true">删除</el-button>
            </template>
            </el-popover> -->

            <el-popover v-model:visible="onlineVisible" :disabled="!multipleSelection.length" placement="top" width="160">
            <p>确定要发布吗？</p>
            <div style="text-align: right; margin-top: 8px;">
                <el-button type="primary" link @click="onlineVisible = false">取消</el-button>
                <el-button type="primary" @click="onLine">确定</el-button>
            </div>
            <template #reference>
                <el-button icon="Position" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="onlineVisible = true">发布</el-button>
            </template>
            </el-popover>
        </div>
        <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        stripe
        height="730"
	      :cell-style="{height: '0px'}" 

        @selection-change="handleSelectionChange" 
        >
        <el-table-column  type="selection" width="40" />
        <el-table-column align="left" label="链接ID" prop="ID" width="80" />
        <el-table-column align="left" label="推广链接" prop="link" width="140" class-name="col-link"  >
            <template #default="scope" >{{ scope.row.link }} 
              <el-button type="primary" link class="copy" @click="copyClick(scope.row.link)" >
                  <el-icon style="margin-right: 5px"><DocumentCopy /></el-icon>
                  点击复制
              </el-button>
            </template>
         </el-table-column>
         <el-table-column align="left" label="启动路径" prop="link" width="140" class-name="col-link"  >
            <template #default="scope" >{{ scope.row.link.split("?")[0]  }} 
              <el-button type="primary" link class="copy" @click="copyClick( scope.row.link.split('?')[0] )" >
                  <el-icon style="margin-right: 5px"><DocumentCopy /></el-icon>
                  点击复制
              </el-button>
            </template>
         </el-table-column>
         <el-table-column align="left" label="启动参数" prop="productLink" width="140" class-name="col-link"  >
            <template #default="scope" >{{ scope.row.productLink }} 
              <el-button type="primary" link class="copy" @click="copyClick(scope.row.productLink)" >
                  <el-icon style="margin-right: 5px"><DocumentCopy /></el-icon>
                  点击复制
              </el-button>
            </template>
         </el-table-column>
         <!-- <el-table-column align="left" label="监测链接" prop="trackLink" width="140" class-name="col-link"  >
            <template #default="scope" >
              <el-tooltip
        	class="item apostrophe"
       		effect="dark"
            :content="scope.row.trackLink"
            placement="top" v-show="scope.row.trackLink!=''">
                <span v-show="scope.row.trackLink!=''">悬停展示</span>
            </el-tooltip>
              <el-button type="primary" link class="copy" @click="copyClick(scope.row.trackLink)" v-show="scope.row.trackLink!=''" >
                  <el-icon style="margin-right: 5px"><DocumentCopy /></el-icon>
                  点击复制
              </el-button>
            </template>
         </el-table-column>
         <el-table-column align="left" label="短链接" prop="shortLink" width="140" class-name="col-link"  >
            <template #default="scope" >{{ scope.row.shortLink }} 
              <el-button type="primary" link class="copy" @click="copyClick(scope.row.shortLink)"  v-show="scope.row.shortLink!=''">
                  <el-icon style="margin-right: 5px"><DocumentCopy /></el-icon>
                  点击复制
              </el-button>
            </template>
         </el-table-column> -->
         <el-table-column align="left" label="平台类型" prop="platId" width="120">
            <template #default="scope">
            {{ filterDict(scope.row.platId,platOptions) }}
            </template>
        </el-table-column>
        <el-table-column align="left" label="推广名称" prop="referralName" width="80"  />
        <el-table-column align="left" label="入口" width="120" class-name="col-link">
            <template #default="scope">{{ scope.row.seqName+' (短剧id:'+scope.row.movieId+') /\n'+scope.row.movieName }}</template>
         </el-table-column>
        <!-- <el-table-column align="left" label="短剧id" prop="movieId" width="120" />
        <el-table-column align="left" label="短剧名称" prop="movieName" width="120" />
        <el-table-column align="left" label="剧集id" prop="episodeId" width="120" /> -->
        <!-- <el-table-column align="left" label="章节名称" prop="seqName" width="120" /> -->
        <el-table-column align="left" label="单集价格（单位分）" prop="moviePrice" width="100" />
        <el-table-column align="left" label="免费集数" prop="epFreeNum" width="60" />
        <!-- <el-table-column align="left" label="媒体来源" prop="source" width="120" /> -->
        <el-table-column align="left" label="回传配置" prop="callbackConfigName" width="100" />
        <!-- <el-table-column align="left" label="充值模板类型" prop="productType" width="120" /> -->
        <!-- <el-table-column align="left" label="价格模板未付费" prop="productIds" width="120" />
        <el-table-column align="left" label="价格模板已付费" prop="productIdsPaid" width="120" /> -->

        <el-table-column align="left" label="新增用户数" prop="newUserCount" width="80" />
        <!-- <el-table-column align="left" label="新增用户充值金额(单位元)" prop="rechargeSum" width="80" /> -->
        <el-table-column align="left" label="充值金额(单位元)" prop="rechargeSum" width="100" />
        <el-table-column align="left" label="充值笔数" prop="rechargeCount" width="80" />
          <el-table-column align="left" label="新增用户付费数" prop="newUserRechargeCount" width="80" />
          <el-table-column align="left" label="付费会员数" prop="useridCountMem" width="80" />

          <el-table-column align="left" label="新增用户付费率" width="80">
            <template #default="scope">{{  scope.row.newUserCount>0 ?(scope.row.newUserRechargeCount/scope.row.newUserCount*100).toFixed(2)+"%" : "0%"}}</template>
         </el-table-column>
         <el-table-column align="left" label="ARPU" width="100">
            <template #default="scope">{{  scope.row.newUserRechargeCount>0 ?(scope.row.rechargeSum/scope.row.newUserRechargeCount).toFixed(2) : "0"}}</template>
         </el-table-column>
         <el-table-column align="left" label="复购用户占比" width="130">
            <template #default="scope">
            1单: {{  scope.row.newUserRechargeCount>0 ?(scope.row.useridCount1/scope.row.newUserRechargeCount*100).toFixed(2)+"%" : "0%"}}<br/>
            2单: {{  scope.row.newUserRechargeCount>0 ?(scope.row.useridCount2/scope.row.newUserRechargeCount*100).toFixed(2)+"%" : "0%"}}<br/>
            3单: {{  scope.row.newUserRechargeCount>0 ?(scope.row.useridCount3/scope.row.newUserRechargeCount*100).toFixed(2)+"%" : "0%"}}<br/>
            >3单: {{  scope.row.newUserRechargeCount>0 ?(scope.row.useridCountGt3/scope.row.newUserRechargeCount*100).toFixed(2)+"%" : "0%"}}
          </template>

         </el-table-column>
        <el-table-column align="left" label="创建人" prop="createUid" width="80" v-auth="btnAuth.createUidShow" />
         <el-table-column align="left" label="创建时间" width="110">
            <template #default="scope">{{ formatDate(scope.row.createTime) }}</template>
         </el-table-column>
         <el-table-column align="left" label="变更时间" width="110">
            <template #default="scope">{{ formatDate(scope.row.updateTime) }}</template>
         </el-table-column>
        <el-table-column align="left" label="操  作" width="120"           fixed="right">
            <template #default="scope">
            <el-button type="primary" link class="table-button" @click="getDetails(scope.row)">
                <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>
                查看详情
            </el-button>
            <el-button type="primary" link class="table-button" @click="getStatistics(scope.row)">
                <el-icon style="margin-right: 5px"><Histogram /></el-icon>
                数据统计
            </el-button>
            <!-- <el-button type="primary" link class="table-button" @click="templateConfiguration(scope.row)">
                <el-icon style="margin-right: 5px"><Histogram /></el-icon>
                  模板配置   
            </el-button> -->
            <el-button type="primary" link icon="edit" class="table-button" @click="updateTReferralFunc(scope.row)">变更</el-button>
            <!-- <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button> -->
            <el-button type="primary" link class="table-button" @click="orderManagement(scope.row)">
                <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>
                订单管理
            </el-button>
            </template>
        </el-table-column>
        </el-table>
        <div class="gva-pagination">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            />
        </div>
    </div>
    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="type==='create'?'添加':'修改'" destroy-on-close>
      <el-scrollbar height="500px">
          <el-form :model="formData" label-position="right" ref="elFormRef" :rules="rule" label-width="140px">
            <el-form-item label="短剧选择:"  prop="movieId" >
              <el-select
                v-model="detailData.movieInfo"
                style="width:100%" placeholder="请选择短剧"
                @change="ChangeEpisodeId"
                value-key="ID"
                :disabled = "true"
                >
                  <el-option
                    v-for="item in movielist"
                    :key="item.ID"
                    :value="item"
                    :label="item.name"
                  >{{item.name}}</el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="剧集id:"  prop="episodeId"  v-show="false" >
              <el-input v-model.number="formData.episodeId" :clearable="true" placeholder="请输入剧集id" :disabled = "true"/>
            </el-form-item>
            <el-form-item label="章节-序号:"  prop="seq" v-show="false"  >
              <el-input v-model.number="formData.seq" :clearable="true" placeholder="请输入章节-序号"   :disabled = "true"/>
            </el-form-item>
            <el-form-item label="章节名称:"  prop="seqName" >
              <el-input v-model="formData.seqName" :clearable="true"  placeholder="请输入章节名称"  :disabled = "true"/>
            </el-form-item>
            <el-form-item label="推广配置名称:"  prop="referralName" >
              <el-input v-model="formData.referralName" :clearable="true"  placeholder="请输入推广渠道名称" />
            </el-form-item>
            <el-form-item label="单集价格(单位:分):"  prop="moviePrice" >
              <el-input v-model.number="formData.moviePrice" :clearable="true" placeholder="自定义单集价格（单位分" @change="search"  />
            </el-form-item>
            <el-form-item label="免费集数:"  prop="epFreeNum" >
              <el-input v-model.number="formData.epFreeNum" :clearable="true" placeholder="自定义免费集数"  />
            </el-form-item>
            <el-form-item label="投放媒体:" prop="source">
                <el-radio-group v-model="formData.source">
                  <el-radio label="dy">抖音</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="回传配置:"  prop="callbackConfigId" >
              <el-select
                v-model.number="formData.callbackConfigId"
                style="width:100%" placeholder="请选择回传配置"
                value-key="ID"
                >
                  <el-option
                    v-for="item in convruleslist"
                    :key="item.ID"
                    :value="item.ID"
                    :label="item.name"
                  />
              </el-select>
            </el-form-item>
            <el-form-item label="未付费充值档位:"  prop="productIds"  v-show="false">
              <el-input v-model="formData.productIds" :clearable="true"  placeholder="请输入未付费充值档位"  />
            </el-form-item>
            <el-form-item label="充值模板 排序:"  prop="productOrder" v-show="false" >
              <el-input v-model="formData.productOrder" :clearable="true"  placeholder="请输入充值模板 排序" />
            </el-form-item>

            <!-- <el-form-item label="充值挽留 档位库id:"  prop="productIdRetain" >
              <el-input v-model="formData.productIdRetain" :clearable="true"  placeholder="请输入充值挽留 档位库id" />
            </el-form-item> -->

          <el-form-item label="已付费充值档位:"  prop="productIdsPaid"  v-show="false">
              <el-input v-model="formData.productIdsPaid" :clearable="true"  placeholder="请输入已付费充值档位" />
            </el-form-item>
            <el-form-item label="充值模板 排序 已付费:"  prop="productOrderPaid"   v-show="false">
              <el-input v-model="formData.productOrderPaid" :clearable="true"  placeholder="请输入充值模板 排序 已付费" />
           </el-form-item>

          <el-form-item label="充值模板类型:" prop="productType">
              <el-radio-group v-model="formData.productType">
                <!-- <el-radio :label="1">通用模板</el-radio> -->
                <el-radio :label="2">自定义模板</el-radio>
              </el-radio-group>
           <el-button
              class="calculateCheckpoint"
              @click="calculateCheckpointData"
              type="primary"
            >
               计算付费卡点
          </el-button>
          </el-form-item>
        
          <el-form-item label="充值模板选择:" prop="productTplUserId">
            <el-select
                  v-model.number="detailData.tplUserInfo"
                  style="width:100%" 
                  placeholder="请选择充值模板"
                  @change="selectChanged"
                  value-key="ID"
                  >
                    <el-option
                      v-for="item in productTplUserList"
                      :key="item.ID"
                      :value="item"
                      :label="item.name"
                    />
            </el-select>
          </el-form-item>

          </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <el-dialog v-model="detailShow" style="width: 800px" lock-scroll :before-close="closeDetailShow" title="查看详情" destroy-on-close>
      <el-scrollbar height="550px">
        <el-descriptions column="1" border>
                <el-descriptions-item label="短剧id">
                        {{ formData.movieId }}
                </el-descriptions-item>
                <el-descriptions-item label="剧集id">
                        {{ formData.episodeId }}
                </el-descriptions-item>
                <el-descriptions-item label="章节-序号">
                        {{ formData.seq }}
                </el-descriptions-item>
                <el-descriptions-item label="章节名称">
                        {{ formData.seqName }}
                </el-descriptions-item>
                <el-descriptions-item label="推广渠道名称">
                        {{ formData.referralName }}
                </el-descriptions-item>
                <el-descriptions-item label="媒体来源">
                        {{ formData.source }}
                </el-descriptions-item>
                <el-descriptions-item label="回传分类">
                        {{ formData.callbackType }}
                </el-descriptions-item>
                <el-descriptions-item label="回传配置 自定义方案">
                        {{ formData.callbackConfigId }}
                </el-descriptions-item>
                <el-descriptions-item label="充值模板类型">
                        {{ formData.productType }}
                </el-descriptions-item>
                <!-- <el-descriptions-item label="充值模板 集合">
                        {{ formData.productIds }}
                </el-descriptions-item>
                <el-descriptions-item label="充值模板 排序">
                        {{ formData.productOrder }}
                </el-descriptions-item>
                <el-descriptions-item label="充值模板 集合 已付费">
                        {{ formData.productIdsPaid }}
                </el-descriptions-item>
                <el-descriptions-item label="充值模板 排序 已付费">
                        {{ formData.productOrderPaid }}
                </el-descriptions-item>
                <el-descriptions-item label="充值挽留 档位库id">
                        {{ formData.productIdRetain }}
                </el-descriptions-item> -->
                <el-descriptions-item label="推广链接">
                        {{ formData.link }}
                </el-descriptions-item>
                <el-descriptions-item label="推广链接-短链">
                        {{ formData.shortLink }}
                </el-descriptions-item>
                <!-- <el-descriptions-item label="createUid字段">
                        {{ formData.createUid }}
                </el-descriptions-item>
                <el-descriptions-item label="createTime字段">
                      {{ formatDate(formData.createTime) }}
                </el-descriptions-item>
                <el-descriptions-item label="updateUid字段">
                        {{ formData.updateUid }}
                </el-descriptions-item>
                <el-descriptions-item label="updateTime字段">
                      {{ formatDate(formData.updateTime) }}
                </el-descriptions-item> -->
        </el-descriptions>
      </el-scrollbar>
    </el-dialog>
    
    <el-dialog v-model="statisticsShow" style="width: 800px" lock-scroll :before-close="closeStatisticsShow" title="数据统计" destroy-on-close>
        <iframe :src="statisticsShowSrc"  frameborder="0" width="100%" height="600px"></iframe>
    </el-dialog>
    <!-- 图标点击弹框2-->
    <el-dialog
      v-dialog-drag
      v-model="pictureClickUpV2"
      :before-close="ClosePictureClickUpV2"
      width="1000px"
      :close-on-click-modal="false"
      title="查找带回"
    >
      <el-form
        ref="detailform"
        :label-position="labelPosition"
        label-width="80px"
        style="margin-left: 3%"
        :model="newObject"
        :rules="addRules"
      >
        <el-row :gutter="5">
          <el-col :span="8">
            <el-form-item
              label="平台:"
              prop="platId"
            >
              <el-select
                v-model="newObject.platId"
                filterable
                allow-create
                placeholder="请选择"
                style="width: 240px !important"
              >
                <el-option label="--请选择--" value="0" />
                <el-option label="IOS" value="1" />
                <el-option label="安卓" value="2" />
                <el-option label="web站" value="3" />
                <el-option label="快应用" value="4" />
                <el-option label="web小程序" value="5" />
                <el-option label="KYY免费" value="6" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="包名:"
              prop="appId"
            >
              <el-select
                v-model="newObject.appId"
                filterable
                allow-create
                placeholder="请选择"
                style="width: 240px !important"
              >
                <el-option label="--请选择--" value="0" />
                <el-option label="月鼠小剧场" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="渠道ids:"
              prop="channelId"
            >
              <el-input
                v-model="newObject.channelId"
                style="width: 240px !important"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="8">
            <el-form-item
              label="产品标识:"
              prop="mode"
            >
              <el-input
                v-model="newObject.mode"
                style="width: 240px !important"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="产品名称:"
              prop="productName"
            >
              <el-input
                v-model="newObject.productName"
                style="width: 240px !important"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="是否有效:"
              prop="status"
            >
              <el-select
                v-model="newObject.status"
                filterable
                allow-create
                placeholder="请选择"
                style="width: 240px !important"
              >
                <el-option label="--有效--" value="0" />
                <el-option label="全部" value="1" />
                <el-option label="无效" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="8">
            <el-button
              @click="aa"
            >
              查询
            </el-button>
          </el-col>
          <el-col :span="8">
            <el-button
              @click="selectiveBackV2"
            >
              选择带回
            </el-button>
          </el-col>
          <el-col :span="8" />
        </el-row>
        <el-table
          ref="form"
          v-loading="listLoading"
          :data="callList"
          style="width: 100%"
          @selection-change="setSelectRows"
        >
          <el-table-column type="selection" />

          <el-table-column
            label="ID"
            prop="ID"
            width="120"
          />
          <el-table-column
            label="平台"
            prop="platId"
            width="120"
          />
          <el-table-column
            label="包名"
            prop="appId"
            width="120"
          />
          <el-table-column
            label="渠道ID"
            prop="channelId"
            width="120"
          />
          <el-table-column
            label="排序"
            prop="orderNum"
          />
          <el-table-column
            label="产品标识"
            prop="productId"
            width="120"
          />
          <el-table-column
            label="产品名称"
            prop="productName"
            min-width="140px"
          />
          <el-table-column
            label="实际价格"
            prop="cost"
            min-width="140px"
          />
          <el-table-column
            label="原价"
            prop="originCost"
            min-width="140px"
          />
          <el-table-column
            label="赠送看点"
            prop="give"
            min-width="140px"
          />
          <el-table-column
            label="样式"
            prop="logoStyle"
            min-width="140px"
          />
          <el-table-column
            label="描述"
            prop="logoDesc"
            min-width="140px"
          />

          <el-table-column
            label="档位底色"
            prop="backgroundColor"
            min-width="140px"
          />
          <el-table-column
            label="是否有效"
            prop="status"
            min-width="140px"
          />
          <el-table-column
            label="创建人"
            prop="createUid"
            min-width="140px"
          />
          <el-table-column
            label="创建时间"
            prop="createTime"
            min-width="140px"
          />
          <el-table-column
            label="更新人"
            prop="orderNum"
            min-width="140px"
          />
          <el-table-column
            label="更新时间"
            prop="updateTime"
            min-width="140px"
          />
        </el-table>
      </el-form>
    </el-dialog>
     <!-- 图标点击弹框V1-->
    <el-dialog
      v-dialog-drag
      v-model="pictureClickUpV1"
      :before-close="ClosePictureClickUpV1"
      width="1000px"
      :close-on-click-modal="false"
      title="查找带回"
    >
      <el-form
        ref="detailform"
        :label-position="labelPosition"
        label-width="80px"
        style="margin-left: 3%"
        :model="newObject"
        :rules="addRules"
      >
        <el-row :gutter="5">
          <el-col :span="8">
            <el-form-item
              label="平台:"
              prop="platId"
            >
              <el-select
                v-model="newObject.platId"
                filterable
                allow-create
                placeholder="请选择"
                style="width: 240px !important"
              >
                <el-option label="--请选择--" value="0" />
                <el-option label="IOS" value="1" />
                <el-option label="安卓" value="2" />
                <el-option label="web站" value="3" />
                <el-option label="快应用" value="4" />
                <el-option label="web小程序" value="5" />
                <el-option label="KYY免费" value="6" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="包名:"
              prop="appId"
            >
              <el-select
                v-model="newObject.appId"
                filterable
                allow-create
                placeholder="请选择"
                style="width: 240px !important"
              >
                <el-option label="--请选择--" value="0" />
                <el-option label="月鼠小剧场" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="渠道ids:"
              prop="channelId"
            >
              <el-input
                v-model="newObject.channelId"
                style="width: 240px !important"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="8">
            <el-form-item
              label="产品标识:"
              prop="mode"
            >
              <el-input
                v-model="newObject.mode"
                style="width: 240px !important"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="产品名称:"
              prop="productName"
            >
              <el-input
                v-model="newObject.productName"
                style="width: 240px !important"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="是否有效:"
              prop="status"
            >
              <el-select
                v-model="newObject.status"
                filterable
                allow-create
                placeholder="请选择"
                style="width: 240px !important"
              >
                <el-option label="--有效--" value="0" />
                <el-option label="全部" value="1" />
                <el-option label="无效" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="8">
            <el-button
              @click="aa"
            >
              查询
            </el-button>
          </el-col>
          <el-col :span="8">
            <el-button
              @click="selectiveBackV1"
            >
              选择带回
            </el-button>
          </el-col>
          <el-col :span="8" />
        </el-row>
        <el-table
          ref="form"
          v-loading="listLoading"
          :data="callList"
          style="width: 100%"
          @selection-change="setSelectRows"
        >
          <el-table-column type="selection" />

          <el-table-column
            label="ID"
            prop="ID"
            width="120"
          />
          <el-table-column
            label="平台"
            prop="platId"
            width="120"
          />
          <el-table-column
            label="包名"
            prop="appId"
            width="120"
          />
          <el-table-column
            label="渠道ID"
            prop="channelId"
            width="120"
          />
          <el-table-column
            label="排序"
            prop="orderNum"
          />
          <el-table-column
            label="产品标识"
            prop="productId"
            width="120"
          />
          <el-table-column
            label="产品名称"
            prop="productName"
            min-width="140px"
          />
          <el-table-column
            label="实际价格"
            prop="cost"
            min-width="140px"
          />
          <el-table-column
            label="原价"
            prop="originCost"
            min-width="140px"
          />
          <el-table-column
            label="赠送看点"
            prop="give"
            min-width="140px"
          />
          <el-table-column
            label="样式"
            prop="logoStyle"
            min-width="140px"
          />
          <el-table-column
            label="描述"
            prop="logoDesc"
            min-width="140px"
          />

          <el-table-column
            label="档位底色"
            prop="backgroundColor"
            min-width="140px"
          />
          <el-table-column
            label="是否有效"
            prop="status"
            min-width="140px"
          />
          <el-table-column
            label="创建人"
            prop="createUid"
            min-width="140px"
          />
          <el-table-column
            label="创建时间"
            prop="createTime"
            min-width="140px"
          />
          <el-table-column
            label="更新人"
            prop="orderNum"
            min-width="140px"
          />
          <el-table-column
            label="更新时间"
            prop="updateTime"
            min-width="140px"
          />
        </el-table>
      </el-form>
    </el-dialog>
    <!-- 订单管理抽屉展示列表 -->
    <el-drawer
      v-if="drawerReferralAddFormVisible"
      v-model="drawerReferralAddFormVisible"
      custom-class="auth-drawer"
      :with-header="false"
      size="80%"
      title="订单管理"
    >
      <el-tabs
        :before-leave="autoEnter"
        type="border-card"
      >
        <el-tab-pane label="订单管理">
          <RechargeForm
            ref="referralForm"
            :row="formData"
            @enterReferralAdd="enterReferralAdd"
          />
        </el-tab-pane>

    <!-- <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">
      <el-form-item label="创建日期" prop="createdAt">
      <template #label>
        <span>
          创建日期
          <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </span>
      </template>
      <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始日期" :disabled-date="time=> searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"></el-date-picker>
       —
      <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束日期" :disabled-date="time=> searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"></el-date-picker>
      </el-form-item>
        <el-form-item label="订单ID" prop="name">
         <el-input v-model="searchInfo.orderId" placeholder="订单号" />
        </el-form-item>
           <el-form-item label="支付状态" prop="platId">
            <el-select
                v-model="searchInfo.platId"
                filterable
                allow-create
                placeholder="请选择"
                style="width: 240px !important"
              >
                <el-option label="--全部--" value="0" />
                <el-option label="未支付" value="1" />
                <el-option label="已支付" value="2" />
              </el-select>
      
          </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="getOrderData">查询</el-button>
          <el-button icon="refresh" @click="orderOnReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
        <el-table
          ref="form"
          v-loading="listLoading"
          :data="orderManData"
          style="width: 100%"
          @selection-change="setSelectRows"
        >
          <el-table-column
            label="用户标识"
            prop="userId"
            width="120"
          />
          <el-table-column
            label="订单ID"
            prop="orderId"
            width="120"
          />
          <el-table-column
            label="渠道id"
            prop="channelId"
            width="120"
          />
          <el-table-column
            label="推广id"
            prop="referralId"
            min-width="140px"
          />
          <el-table-column
            label="产品名字"
            prop="productName"
            min-width="140px"
          />
          <el-table-column
            label="产品类型"
            prop="productType"
            min-width="140px"
          />
          <el-table-column
            label="金额（分）"
            prop="productCost"
            min-width="140px"
          />
          <el-table-column
            label="月卡为天数，看点"
            prop="productAmount"
            min-width="140px"
          />
          <el-table-column
            label="赠送金额"
            prop="productGive"
            min-width="140px"
          />
          <el-table-column
            label="短剧ID"
            prop="movieId"
            min-width="140px"
          />
          <el-table-column
            label="短剧聚集id"
            prop="episodeId"
            min-width="140px"
          />
          <el-table-column
            label="阅读序号"
            prop="seq"
            min-width="140px"
          />
          <el-table-column
            label="支付状态"
            prop="payStatus"
            min-width="140px"
          />
          <el-table-column
            label="创建时间"
            prop="createTime"
            min-width="140px"
          />
          <el-table-column
            label="更新时间"
            prop="updateTime"
            min-width="140px"
          />
        </el-table>
        <div class="gva-pagination">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChangeV2"
            @size-change="handleSizeChangeV2"
            />
        </div> -->
      </el-tabs>
    </el-drawer>

  </div>
</template>

<script setup>
import {
  createTReferral,
  deleteTReferral,
  deleteTReferralByIds,
  updateTReferral,
  findTReferral,
  getTReferralList,
  getMovieApi,
  getConvRulesApi,
  refreshTReferralByIds
} from '@/api/tReferral'

import {
  getTProductList,
  getTProductListByIds
} from '@/api/tProduct'

import {
  getTProductTplUserList
} from '@/api/tProductTplUser'

import {
  getTRechargeList
} from '@/api/tRecharge'



import Menus from '@/view/superAdmin/authority/components/menus.vue'
import Apis from '@/view/superAdmin/authority/components/apis.vue'

// 订单管理
import RechargeForm from '@/view/tRecharge/tRecharge.vue'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox, formProps } from 'element-plus'

//引用菜单按钮权限组件
import { useBtnAuth } from '@/utils/btnAuth'
    const btnAuth = useBtnAuth()


// vue3 组件拖动  引入插件
// import draggable from 'vuedraggable';

// import { VueDraggableNext } from 'vue-draggable-next'

import { reactive, toRefs, onMounted, ref,createApp } from 'vue'

let draggedIndex = null;

const onDragStart = (index) => {
  draggedIndex = index;
};

const onDragOver = (event) => {
  event.preventDefault();
};

const onDrop = (targetIndex, event) => {
  event.preventDefault();
  if (draggedIndex !== targetIndex) {
    const draggedOrder = kpList.value[draggedIndex].orderNum;
    const targetOrder = kpList.value[targetIndex].orderNum;
    kpList.value[draggedIndex].orderNum = targetOrder;
    kpList.value[targetIndex].orderNum = draggedOrder;
  }
}

defineOptions({
    name: 'TReferral'
})

const activeName =ref({
  activeName: 'second'
})

// vp添加商品框
const vpShopInfo = ref({
   productName: '',
   ab: '',
   cd: '',
   // 未付费充值档位信息
   productIds: [],
   // 已付费充值档位信息
   productIdsPaid: []
})




// 自动化生成的字典（可能为空）以及字段
const platOptions = ref([])
const formData = ref({
        ID:0,
        movieId: '',
        episodeId: 0,
        seq: 0,
        seqName: '',
        moviePrice: 0,
        epFreeNum: 0,
        referralName: '',
        source: '',
        callbackType: 0,
        callbackConfigId: 0,
        productType: 0,
        productTplUserId: 0,
        productTplUserName: '',

        productIds: '',
        productOrder: '',
        productIdsPaid: '',
        productOrderPaid: '',
        productIdRetain: '',
        link: '',
        shortLink: '',
        createUid: 0,
        createTime: new Date(),
        updateUid: 0,
        updateTime: new Date(),
        })
const detailData = ref({
        productTplUserName: '',
        moviePrice:'',// 每集付费金额
        price:'',// 单集价格事件触发默认的值
        movieInfo:{
          totalCnt:'', // 全集
        },
        tplUserInfo:{}
        })


// 验证规则
const rule = reactive({
    movieId : [{
        required: true,
        message: '',
        trigger: ['input','blur'],
    }
    
  ]
})

const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])

// 未充值卡点集合
const unpaidCardPointsList = ref([])

// 已充值卡点集合
const unpaidCardPointsListV2 = ref([])
// 订单管理
const orderManData = ref([])
const searchInfo = ref({})
// 存放产品名称/描述数组集合
const kpList = ref([])


// 付费卡点弹框
const calculateCheckpointDialog = ref(false)

// 点击计算付费卡点，弹框
const calculateCheckpointData= async(row) => {
    calculateCheckpointDialog.value = true
    // 未充值
    unpaidCardPoints()
    // 已充值
    unpaidCardPointsV2()
}

// 关闭付费卡点弹窗
const closecalculateCheckpointDialog = async() => {
   calculateCheckpointDialog.value = false
}

// 订单管理抽屉列表
const drawerReferralAddFormVisible = ref(false)


// 子组件控制关闭
const enterReferralAdd = (close) => {
    drawerReferralAddFormVisible.value = close
}


// 订单管理方法(抽屉展示)
const orderManagement= async(row) => {
  formData.value = row
  // 打开抽屉
  drawerReferralAddFormVisible.value = true 
}


// 普通充值添加商品弹框
const ptShopInfo=ref({
  productName:''
})

// vip添加商品table数据
const vpShopList=ref([])

// 普通
const vpShopListV=ref([])

// 订单重置
const orderOnReset = () => {
  searchInfo.value = {}
  orderPaging()
}

// 订单查询
const getOrderData =() => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    orderPaging()
  })
}


// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}


// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleSizeChangeV1 =(val) =>{
  pageSize.value = val
  handelInputV5()
}


// 抽屉分页
const handleCurrentChangeV2 =(val) =>{
  page.value = val
  orderPaging()
}

const handleSizeChangeV2 =(val) =>{
  pageSize.value = val
  orderPaging()
}

const handleCurrentChangeV1 =(val) =>{
  page.value = val
  handelInputV5()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}


// 选项卡筛选数据
const handleTabClick = async(tab, event) => {
  if (tab.index == 0) {
     if (vpShopInfo.value.productIdsPaid != null) {
        const idList = vpShopInfo.value.productIdsPaid
        const idArray = idList.split(',')
        const ids = []
        for(var i = 0; i<idArray.length; i++){
          ids.push(parseInt(idArray[i]))
        }
        let {data}  = await getTProductListByIds({ ids })
        kpList.value = data.list
      }
  } else if (tab.index == 1) {
      if (vpShopInfo.value.productIds != null) {
         // 未付费用户
         const idList = vpShopInfo.value.productIds
         const idArray = idList.split(',')
         const ids = []
         for(var i = 0; i<idArray.length; i++){
          ids.push(parseInt(idArray[i]))
        }
        let {data}  = await getTProductListByIds({ ids })
        kpList.value = data.list
      } 
    }
}

// 选择
const chooseData = async(row) => {   
  kpList.value.push(row)
  // vpShopInfo.value.productName = row.productName
   // 根据当前选中的产品名称去查询档位数据
   handelInputV6()
   // 关闭添加弹框
   closeAddShopShow()
}
const restVpDataV1 = async() => {
    // 清空文本框
    vpShopInfo.value.productName = ''
    handelInputV7()
}
const getVpDataByProductNameV1 = async() => {
  handelInputV7()
}
// vp查询,根据产品名称查询
const getVpDataByProductName = async() => {
  handelInputV6()
}

// 点击重置,重置文本框内容
const restVpData = async() => {
  // 清空文本框
  vpShopInfo.value.productName = ''
  // 渲染页面调用查询方法
  handelInputV5()
}

const orderNumChangeV1 =async() => {
  // 根据输入的排序值,对list集合进行排序
  payList.value.sort((a, b) => a.orderNum - b.orderNum)
      formData.value.productIdsPaid = ''
      for (var i = 0; i < payList.value.length; i++) {
        if (i > 0) {
          formData.value.productIdsPaid += ','
        }
        formData.value.productIdsPaid += payList.value[i].ID
      }
 }

// 排序channge事件
const orderNumChange =async() => {
       // 根据输入的排序值,对list集合进行排序
      topUpList.value.sort((a, b) => a.orderNum - b.orderNum)
      formData.value.productIds = ''
      for (var i = 0; i < topUpList.value.length; i++) {
        if (i > 0) {
          formData.value.productIds += ','
        }
        formData.value.productIds += topUpList.value[i].ID
      }
  }

// 查询
const getTableData = async() => {
  const table = await getTReferralList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize


    for(var i=0; i<tableData.value.length; i++){
  
        var strs = tableData.value[i].link.split('?')[1].split("&");  //将得到的参数分隔成数组[id="123456",name="www"];
        var object = {};
        for (var j = 0; j < strs.length; j++) {
          object[strs[j].split("=")[0]] = strs[j].split("=")[1];
        }
        tableData.value[i].productLink=tableData.value[i].link.split('?')[1]
        if (!object['tt_album_id']&&!object['tt_episode_id']){
          tableData.value[i].productLink=tableData.value[i].link.split('?')[1]
          // +tableData.value[i].link.split('?')[1]+"?"
          // +'&channelId='+object.albumIdTt
          // +'&referralId='+object.albumIdTt
          // +'&source='+object.albumIdTt
          // +'&jumpPage='+object.albumIdTt
          // +'&adtype='+object.albumIdTt
          // +'&albumIdWx='+object.albumIdTt

          +'&tt_album_id='+object.albumIdTt
          +'&tt_episode_id='+object.episodeIdTt
        }
    }
  }
}
getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () =>{
  platOptions.value = await getDictFunc('plat')
}

// 获取需要的字典 可能为空 按需保留
setOptions()


// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}

// 多选数据


// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
            deleteTReferralFunc(row)
        })
    }


// 批量删除控制标记
const deleteVisible = ref(false)

// 多选删除
const onDelete = async() => {
      const ids = []
      if (multipleSelection.value.length === 0) {
        ElMessage({
          type: 'warning',
          message: '请选择要删除的数据'
        })
        return
      }
      multipleSelection.value &&
        multipleSelection.value.map(item => {
          ids.push(item.ID)
        })
      const res = await deleteTReferralByIds({ ids })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        if (tableData.value.length === ids.length && page.value > 1) {
          page.value--
        }
        deleteVisible.value = false
        getTableData()
      }
    }

    // 批量发布控制标记
const onlineVisible = ref(false)

// 多选删除
const onLine = async() => {
      const ids = []
      if (multipleSelection.value.length === 0) {
        ElMessage({
          type: 'warning',
          message: '请选择要发布更新的数据'
        })
        return
      }
      multipleSelection.value &&
        multipleSelection.value.map(item => {
          ids.push(item.ID)
        })
      const res = await refreshTReferralByIds({ ids })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '发布成功'
        })
        onlineVisible.value = false
      }
    }

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateTReferralFunc = async(row) => {
  // 每集付费金额
  detailData.value.moviePrice= row.moviePrice 
  // 获取免费集数
  detailData.value.freeEpisodes= row.epFreeNum
  //已付费充值档位
  vpShopInfo.value.productIdsPaid = row.productIdsPaid
    const res = await findTReferral({ ID: row.ID })
    type.value = 'update'
    if (res.code === 0) {
        formData.value = res.data.retReferral
        detailData.value.movieInfo=movielist.value.filter(item => item.ID==row.movieId )[0]
        detailData.value.tplUserInfo=productTplUserList.value.filter(item => item.ID==row.productTplUserId )[0]
        dialogFormVisible.value = true
    }
    //在根据ids查询列表数据
    abcList1()
    abcList2()
}
 

// 单集价格input输入框事件
 const search = async(event) => {
  detailData.value.price = event
}

// 未充值付费卡点详情
const unpaidCardPoints= async() => {
    if(detailData.value.tplUserInfo.productIds != null) {
      const idList =  detailData.value.tplUserInfo.productIds
      const idArray = idList.split(',')
      const ids = []
      for(var i = 0; i<idArray.length; i++){
        ids.push(parseInt(idArray[i]))
      }
      let data = await getTProductListByIds({ ids }).then(response =>{  
        const idSelectList = JSON.parse(JSON.stringify(response.data.list)) 
        for(var j=0; j<idSelectList.length; j++){
          idSelectList[j].shopNum = j + 1
          // 模板名称
          idSelectList[j].name = detailData.value.tplUserInfo.name

        if(detailData.value.price == null || detailData.value.price ==""){
          if(detailData.value.moviePrice != 0) {
             idSelectList[j].remainingHighlights = (idSelectList[j].amount + idSelectList[j].give) % detailData.value.moviePrice
          } else {
             idSelectList[j].remainingHighlights = 0    
         }   
        }else {
          if(detailData.value.price != 0) {
             idSelectList[j].remainingHighlights = (idSelectList[j].amount + idSelectList[j].give) % detailData.value.price
          } else {
             idSelectList[j].remainingHighlights = 0    
         }   
      }
       
      if(detailData.value.price == null || detailData.value.price ==""){
        if(detailData.value.moviePrice != 0){
          // 预计可播放集数
          idSelectList[j].episodes = Math.floor((idSelectList[j].amount  + idSelectList[j].give) / detailData.value.moviePrice)
         } else {
            idSelectList[j].episodes = 0
         }
      }else {
        if(detailData.value.price != 0){
          // 预计可播放集数
          idSelectList[j].episodes = Math.floor((idSelectList[j].amount  + idSelectList[j].give) / detailData.value.price)
         } else {
            idSelectList[j].episodes = 0
         }
      }
      
          // vip全集
           idSelectList[j].totalCnt = detailData.value.movieInfo.totalCnt
           idSelectList[j].vpDay = (idSelectList[j].amount + idSelectList[j].give) / 86400
           if(isNumber(idSelectList[j].vpDay)){
            idSelectList[j].vpDay = ((idSelectList[j].amount + idSelectList[j].give) / 86400)
           } else {
              idSelectList[j].vpDay = ((idSelectList[j].amount + idSelectList[j].give) / 86400).toFixed(2)
           }
        }
         unpaidCardPointsList.value = idSelectList
      })
    }
 }

 // 判断输出的对象是小数还是整数，小数则保留两位小数值，整数则不需要
 const isNumber = (value) =>{
  return /^\d+(\d+)?$/.test(value);
 }

 // 已充值付费卡点详情
 const unpaidCardPointsV2= async() => {
    if(detailData.value.tplUserInfo.productIdsPaid != null) {
      const idList =  detailData.value.tplUserInfo.productIdsPaid
      const idArray = idList.split(',')
      const ids = []
      for(var i = 0; i<idArray.length; i++){
        ids.push(parseInt(idArray[i]))
      }
      let data = await getTProductListByIds({ ids }).then(response =>{
        const idSelectList = JSON.parse(JSON.stringify(response.data.list))
        for(var i=0; i<idSelectList.length;i++){
          // 模板商品排序
          idSelectList[i].shopNum = i+1
          idSelectList[i].name = detailData.value.tplUserInfo.name
            
          if(detailData.value.price == null || detailData.value.price == ""){
            if(detailData.value.moviePrice !=0){
             // 剩余看点 
             idSelectList[i].remainingHighlights = (idSelectList[i].amount + idSelectList[i].give) % detailData.value.moviePrice
          }else {
             idSelectList[i].remainingHighlights = 0
          }
        }else {
          if(detailData.value.price !=0){
             // 剩余看点 
             idSelectList[i].remainingHighlights = (idSelectList[i].amount + idSelectList[i].give) % detailData.value.price
          }else {
             idSelectList[i].remainingHighlights = 0
          }
        }
        if (detailData.value.price == null || detailData.value.price == "") {
              // 预计可播放集数
          if(detailData.value.moviePrice !=0){
            idSelectList[i].episodes = Math.floor((idSelectList[i].amount + idSelectList[i].give) / detailData.value.moviePrice)
          }else {
            idSelectList[i].episodes = 0
          }
        }else {
           // 预计可播放集数
           if(detailData.value.price !=0){
            idSelectList[i].episodes = Math.floor((idSelectList[i].amount + idSelectList[i].give) / detailData.value.price)
          }else {
            idSelectList[i].episodes = 0
          }
        }
          // 总集数
          idSelectList[i].totalCnt = detailData.value.movieInfo.totalCnt 
          
          // VIP 天数
          idSelectList[i].vpDay = (idSelectList[i].amount + idSelectList[i].give) / 86400
           if(isNumber(idSelectList[i].vpDay)){
            idSelectList[i].vpDay = ((idSelectList[i].amount + idSelectList[i].give) / 86400)
           } else {
              idSelectList[i].vpDay = ((idSelectList[i].amount + idSelectList[i].give) / 86400).toFixed(2)
           }
        }
        unpaidCardPointsListV2.value = idSelectList
      })
    }
 }


// 删除行
const deleteTReferralFunc = async (row) => {
    const res = await deleteTReferral({ ID: row.ID })
    if (res.code === 0) {
        ElMessage({
                type: 'success',
                message: '删除成功'
            })
            if (tableData.value.length === 1 && page.value > 1) {
            page.value--
        }
        getTableData()
    }
}

// vip充值 商品点击方法
const vpAddClick = () => {
  // 打开弹窗
  openAddShopShow()
  // 查询档位数据,渲染table页
  handelInputV5()
}

// 未充值挡位数据/已充值档位数据
const gearsData = async() => {   
  const data = await getTProductList().then(response =>{
    kpList.value = response.data.list
  })
}

// 根据产品名称查询档位数据
const handelInputV6  = async() => {
  const {data} = await getTProductList(vpShopInfo.value.productName)
  vpShopList.value =data.list
}

const handelInputV7  = async() => {
  const {data} = await getTProductList(vpShopInfo.value.productName)
  vpShopListV.value =data.list
}


// 普通充值页配置 根据产品名称查询
const getCollectionList = async() =>{
  const {data} = await getTProductList(ptShopInfo.value.productName)
  vpShopListV.value = data.list
}

// 普通充值页配置/添加页面/重置按钮
const restPtData = async() =>{
  ptShopInfo.value.productName = ''
  addPtGearsData()
}

// 普通充值页配置/添加商品文件
const addPtGearsData = async() => {
    const table= await getTProductList({page: page.value, pageSize: pageSize.value, ...searchInfo.value})
    vpShopListV.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
}


// 查询档位数据,渲染table页
const handelInputV5  = async() => {
    const table= await getTProductList({page: page.value, pageSize: pageSize.value, ...searchInfo.value})
    vpShopList.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
}

// 编辑弹框
const upGearsPage =() =>{
  updateShopShow.value = true
  addPtGearsData()
}

// vip 添加商品弹窗
const openAddShopShow = ()=>{
  addShopShow.value = true
}

// 普通充值 商品点击方法
const ptAddClick = () =>{
  openPtAddClick()
  // 调用添加查询方法
  addPtGearsData()
}   
// 普通充值 添加商品弹窗
const openPtAddClick= () =>{
  tpAddShopShow.value = true
}


// 打开档位查询弹窗
const getSearchProductDetails = async (row) => {
  // 打开弹窗
  openSearchProductShow()
}

// 查看档位查询弹窗标记
const searchProductShow = ref(false)


// 打开档位查询弹窗
const openSearchProductShow = () => {
  searchProductShow.value = true
}


// 弹窗控制标记
const dialogFormVisible = ref(false)


// 查看详情控制标记
const detailShow = ref(false)

// 模板配置控制标记
const templateShow = ref(false)

// VP添加商品控制编辑
const addShopShow = ref(false)

// 编辑控制按钮
const updateShopShow = ref(false)

// 普通商品控制编辑
const tpAddShopShow = ref(false)


// 关闭模板配置控制弹窗
const closeTemplateShow = () => {
  templateShow.value = false
}

// 关闭vip 添加商品控制弹框
const closeAddShopShow = ()=>{
  addShopShow.value = false
}

const closeUpdateShopShow = ()=>{
  updateShopShow.value = false
}

// 关闭普通 添加商品控制弹框
const closeptAddShopShow =()=>{
  tpAddShopShow.value =false
}

const referralData = ref([])

const getReferralData = async() => {
  const tableZ = await getTReferralList({ page: 1, pageSize: 1000 })
  if (tableZ.code === 0) {
    referralData.value = tableZ.data.list

  }
}
// 查看数据统计弹窗标记
const statisticsShow = ref(false)

const statisticsShowSrc= ref('')

// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}

// 模板配置弹窗详情 
const openTemplateConfigurationShow = () => {
   // 打开模板配置弹窗
  templateShow.value = true
  // 默认打开弹窗已充值用户
  gearsData()
}

// 打开数据统计弹窗
const openStatisticsShow = () => {
  statisticsShow.value = true
}

// 打开详情
const getDetails = async (row) => {
  // 打开弹窗
  const res = await findTReferral({ ID: row.ID })
  if (res.code === 0) {
    formData.value = res.data.retReferral
    openDetailShow()
  }
}
// 模板配置
const templateConfiguration = async (row) => {
   //未付费充值档位
   vpShopInfo.value.productIds = row.productIds
   //已付费充值档位
   vpShopInfo.value.productIdsPaid = row.productIdsPaid
  // 打开模板配置弹窗
  openTemplateConfigurationShow()
}
// 打开数据统计
const getStatistics = async (row) => {
  // 打开弹窗
  if (row) {
    statisticsShowSrc.value = 'https://bi.api.tjtlzskj.cn:8103/web/recharge/statistics?referralId='+row.ID
    openStatisticsShow()
  }else{
    const tableZ = await getTReferralList({ page: 1, pageSize: 1000 })
    if (tableZ.code === 0) {
      const ids= tableZ.data.list.map((item)=>{
        return item.ID;
      })
      if(tableZ.data.list.length===0){
        return true
      }
      statisticsShowSrc.value = 'https://bi.api.tjtlzskj.cn:8103/web/recharge/statistics?referralIds='+ids+'&operUid='+tableZ.data.list[0].createUid
      openStatisticsShow()
    }

  }
}
// 关闭详情弹窗
const closeStatisticsShow = () => {
  statisticsShow.value = false
  // formData.value = {
        
  //         }
}

// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  formData.value = {
          movieId: 0,
          episodeId: 0,
          seq: 0,
          seqName: '',
          moviePrice: 0,
          epFreeNum: 0,
          referralName: '',
          source: '',
          callbackType: 0,
          callbackConfigId: 0,
          productType: 0,
          productIds: '',
          productOrder: '',
          productIdsPaid: '',
          productOrderPaid: '',
          productIdRetain: '',
          link: '',
          shortLink: '',
          createUid: 0,
          createTime: new Date(),
          updateUid: 0,
          updateTime: new Date(),
          }
}


// 打开弹窗
const openDialog = () => {
    type.value = 'create'
    // 新增 清空列表
    topUpList.value = []
    payList.value = []
    dialogFormVisible.value = true
    formData.value = {
        seq: 1,
        seqName: '第1集',
   }
}

// 关闭弹窗
const closeDialog = () => {
    dialogFormVisible.value = false

    formData.value = {
        movieId: 0,
        episodeId: 0,
        seq: 0,
        seqName: '',
        moviePrice: 0,
        epFreeNum: 0,
        referralName: '',
        source: '',
        callbackType: 0,
        callbackConfigId: 0,
        productType: 0,
        productTplUserId: 0,
        productTplUserName: '',

        productIds: '',
        productIdsVq: '',
        productOrder: '',
        productIdsPaid: '',
        productIdsPaidVq: '',
        productOrderPaid: '',
        productIdRetain: '',
        productIdList: '',
        productIdsPaidList: '',
        link: '',
        shortLink: '',
        createUid: 0,
        createTime: new Date(),
        updateUid: 0,
        updateTime: new Date(),
     }
}
// 弹窗确定
const enterDialog = async () => {
     elFormRef.value?.validate( async (valid) => {
             if (!valid) return
              let res
              switch (type.value) {
                case 'create':
                  res = await createTReferral(formData.value)
                  break
                case 'update':
                  res = await updateTReferral(formData.value)
                  break
                default:
                  res = await createTReferral(formData.value)
                  break
              }
              if (res.code === 0) {
                ElMessage({
                  type: 'success',
                  message: '创建/更改成功'
                })
                closeDialog()
                getTableData()
              }
      })
}
const movielist = ref([])
const getMovielist = async() => {
  const res = await getMovieApi()
  if (res.code === 0) {
    movielist.value = res.data.list
  }
}
getMovielist()


const convruleslist = ref([])
const getConvRuleslist = async() => {
  const res = await getConvRulesApi()
  if (res.code === 0) {
    convruleslist.value = res.data.list
  }
}
getConvRuleslist()


const ChangeEpisodeId = async (e)  => {
  formData.value.movieId=e.ID
  formData.value.episodeId=e.firstSid
}


//档位带回
const callList = ref([])
const abnList = ref([])
const payList = ref([])
const abcList = ref([])
const selectRows = ref([])
const idList = ref([])
const aa = ref([])
const idsList = ref([])
const gearPositionList = ref([])
const gearPositionListV1 = ref([])
const topUpList = ref([])
const dhList = ref([])
const dsList = ref([])

const newObject= ref({
        orderNum: '',
        amount: '',
        mode: '',
        channelId: '',
        appId: '',
        platId: ''
      })
const tgObj= ref({

        productIds: '',
        callbackConfigId: '',
        referralName: '',
        source: '',
        episodeId: '',
        movieId: '',
        productIdsPaid: '',
        id: ''
      })      
// 弹窗控制标记
const pictureClickUpV1 = ref(false)

const pictureClickUpV2 = ref(false)

const pictureClickV2 = () =>{

  pictureClickUpV1.value = true
  if(formData.value.productIds !=='undefined' && formData.value.productIds !=null && formData.value.productIds !==""){
    formData.value.productIdList = formData.value.productIds+','
  } else {
    formData.value.productIdList = formData.value.productIds
  }
  handelInputV2()
}

const pictureClickV3 = () =>{
  pictureClickUpV2.value = true
  if(formData.value.productIdsPaid !=='undefined' && formData.value.productIdsPaid !=null && formData.value.productIdsPaid !==""){
    formData.value.productIdsPaidList = formData.value.productIdsPaid+','
  } else {
    formData.value.productIdsPaidList = formData.value.productIdsPaid
  }
  handelInputV3()
}
const ClosePictureClickUpV2 = () => {
      pictureClickUpV2.value = false
}
    // 编辑关闭查找带回弹框
const ClosePictureClickUpV1 = () => {
      pictureClickUpV1.value = false
}
    // 推广管理/编辑/配置模板V2
    const handelInputV2  = async() => {
      const { data } = await getTProductList()
      callList.value = data.list
      for (var j in callList) {
        if (data[j] != null) {
          abnList.push(data[j])
        }
      }
    }
    // 推广管理/编辑/配置模板V3
const handelInputV3  = async() => {
      const { data } = await getTProductList()
      callList.value = data.list
      for (var j in callList) {
        // eslint-disable-next-line no-empty
        if (data[j] != null) {
          abcList.push(data[j])
        }
      }
    }
    const setSelectRows= (val) => {
      selectRows.value = val
    } 
    

    // 编辑选择带回(已付费充值档位)
    const selectiveBackV2  = async() => {

      const rows = selectRows.value
   
      if (rows == null || rows.length === 0) {
        this.$message.error('未选中任何数据......')
        return
      }

      const selectIds = []
      
      for (let i = 0; i < rows.length; i++) {
        selectIds.push(rows[i].ID)
      }
      const setIds = new Set(selectIds)
      
      const setIdList =Array.from(setIds).toString()
    
      if (formData.value.productIdsPaidList !=null) {
          // 回显文本框内容
          formData.value.productIdsPaidVq = formData.value.productIdsPaidList + setIdList 
          let arrList = formData.value.productIdsPaidVq.split(',')
          let set = new Set(arrList)
          arrList = Array.from(set)
          formData.value.productIdsPaid = Array.from(arrList).toString()
      } else {
        formData.value.productIdsPaid = setIdList
      }
      // 关闭点击弹框
       ClosePictureClickUpV2()
      
       abcList2()

    }

  // 根据排序字段排序
  const handelInputByOrderNum = async(row) => {
    topUpList.value.sort((a, b) => a.orderNum - b.orderNum)
  }

    // 编辑选择带回 
const selectiveBackV1  = async() => {
      const rows = selectRows.value
      if (rows == null || rows.length === 0) {
        this.$message.error('未选中任何数据......')
        return
      }
      const selectIds = []
      
      for (let i = 0; i < rows.length; i++) {
         selectIds.push(rows[i].ID)
      }
      const setIds = new Set(selectIds)
      const setIdList =Array.from(setIds).toString()
      if (formData.value.productIdList !=null) {
          // 回显文本框内容
          formData.value.productIdsVq = formData.value.productIdList + setIdList
          let arrList = formData.value.productIdsVq.split(',')
          let set = new Set(arrList)
          arrList = Array.from(set)
          formData.value.productIds = Array.from(arrList).toString()
      } else {
        formData.value.productIds = setIdList
      }
      // 关闭点击弹框
       ClosePictureClickUpV1() 
       abcList1()
    }
    
   // 删除档位信息
   const delGearsData = async(item) =>{
      // 根据主键id删除档位信息
      const res = await deleteTReferral({ ID: item })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        gearsData()
      }
    }

    // 删除查询带回数据
    const handleDelete = async (row) => {
      const index = topUpList.value.indexOf(row)
      topUpList.value.splice(index, 1)
      var idsList = formData.value.productIds.split(',')
      var idsLastList = []
      for (var i = 0; i < idsList.length; i++) {
        if (idsList[i] !== row.ID.toString()) {
          idsLastList.push(idsList[i])
        }
      }
      formData.value.productIds = idsLastList.toString()
    }

    // 已付费充值档位   删除查询带回数据
    const handleDeleteV3 = async (row) => {
      const index = payList.value.indexOf(row)
      payList.value.splice(index, 1)
      var idsList = formData.value.productIdsPaid.split(',')
      var idsLastList = []
      for (var i = 0; i < idsList.length; i++) {
        if (idsList[i] !== row.ID.toString()) {
          idsLastList.push(idsList[i])
        }
      }
      formData.value.productIdsPaid = idsLastList.toString()
    }
    
     
    // 已付费充值档位
    const abcList2  = async() => {
      if (formData.value.productIdsPaid != null) {
        const idList = formData.value.productIdsPaid
        const idArray = idList.split(',')
        const ids = []
        for(var i = 0; i<idArray.length; i++){
          ids.push(parseInt(idArray[i]))
        }
      
        let data  = await getTProductListByIds({ ids }).then(response=>{
          gearPositionList.value = formData.value.productIdsPaid.split(',')
         
          for (var i in response.data.list) {
            for (let j = 0; j < gearPositionList.value.length; j++) {
              if (i === gearPositionList.value[j]) {
                abcList.value.push(response.data.list[i])
              }
            }
          }
        })
        const idSelectListF =JSON.parse(JSON.stringify(abcList.value))
        dsList.value = unique(idSelectListF)
        dsList.value.then(response => {  
        payList.value = response
        })
      }
    }

    const abcList1  = async() => {
      topUpList.value = []
      if (formData.value.productIds != null) {
        const idList = formData.value.productIds
        const idArray = idList.split(',')
        const ids = []
        for(var i = 0; i<idArray.length; i++){
          ids.push(parseInt(idArray[i]))
        }
        let data = await getTProductListByIds({ ids }).then(response =>{
          gearPositionList.value = formData.value.productIds.split(',')
          abcList.value = []
          for (var i in response.data.list) {
          for (let j = 0; j < gearPositionList.value.length; j++) {
            if (i === gearPositionList.value[j]) {
              abnList.value.push(response.data.list[i])
            }
          }
        }
      })
        const idSelectList = JSON.parse(JSON.stringify(abnList.value))
        dhList.value = unique(idSelectList)
        dhList.value.then(response => {
        topUpList.value = response
        })
      }
    }

    const unique  = async(arr) => {
      const res = new Map()
      return arr.filter((arr) => !res.has(arr.ID) && res.set(arr.ID, 1))
    }

const productTplUserList = ref([])
const getProductTplUserList = async() => {
  const res = await getTProductTplUserList()
  if (res.code === 0) {
    productTplUserList.value = res.data.list
  }
}
getProductTplUserList()

const selectChanged = async (e)  => {
  formData.value.productTplUserId=e.ID
  formData.value.productIds=e.productIds
  formData.value.productOrder=e.productOrder
  formData.value.productIdsPaid=e.productIdsPaid
  formData.value.productOrderPaid=e.productOrderPaid
  formData.value.productTplUserName=e.name

}   
import Clipboard from 'clipboard'

const copyClick = async (code) => {
  let clipboard = new Clipboard('.copy', {
    text: function () {
      return code
    }
  })
  clipboard.on('success', (e) => {
      ElMessage({
          type: 'success',
          message: '复制成功'
        })
  console.log('复制成功', e)
  // 释放内存
  clipboard.destroy()
  })
    clipboard.on('error', (e) => {
      ElMessage({
            type: 'error',
            message: '复制失败，该浏览器不支持自动复制'
          })
  // 不支持复制
  console.log('该浏览器不支持自动复制', e)
  // 释放内存
  clipboard.destroy()
  })
}

</script>

<style>

/* 计算付费卡点按钮 */
.calculateCheckpoint{
   position: relative;
   left: 75px;
}

.box {
  display: flex;
  flex-wrap: wrap; 
  width: 450px 
}

ul li{
  /* margin-bottom: 10px */
   line-height: 20px
}
.admin-box .el-table .col-link .cell{
  line-height: 16px
}
.admin-box .el-table td .cell{
  line-height: 24px
}

.item {
  width: 120px;
  height: 120px;
  border: 1px solid #ccc;
  background-color: #f3f3f3;
  margin: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  cursor: move;
  user-select: none;
  transition: background-color 0.3s;
  margin-bottom: 45px
}
.item:active {
  background-color: #ddd;
}
</style>
